import numpy as np
import cv2 as cv


def test(target_path, match_path):
    img_target = cv.imread(target_path, cv.IMREAD_GRAYSCALE)
    img_match = cv.imread(match_path, cv.IMREAD_GRAYSCALE)

    # 初始化ORB检测器
    orb = cv.ORB_create()

    # 检测关键点和计算描述子
    kp_target, des_target = orb.detectAndCompute(img_target, None)
    kp_match, des_match = orb.detectAndCompute(img_match, None)

    # 创建BFMatcher对象并进行匹配
    bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True)

    # 进行特征匹配, 返回一个DMatch对象的列表，每个DMatch对象包含了匹配对的信息，如匹配的图像索引、特征点索引和距离等
    matches = bf.match(des_target, des_match)

    # 按照距离排序，距离越小匹配越好
    matches = sorted(matches, key=lambda x: x.distance)

    # 绘制匹配结果（显示前10个匹配）
    img_draw = cv.drawMatches(img_target, kp_target, img_match, kp_match, matches[:10], None,
                              flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

    # 缩放图像以适应屏幕大小（如果需要）
    img_draw = cv.resize(img_draw, None, fx=1, fy=1)

    # 显示匹配结果
    cv.imshow("", img_draw)
    cv.waitKey()
    cv.destroyAllWindows()


if __name__ == '__main__':
    test("../pic/box.png", "../pic/box_in_scene.png")
